<?php


namespace app\api\controller;


use app\common\controller\WeChat;
use printer\HttpClient;
use think\Controller;
use think\Db;
use think\Exception;
use think\Session;
use WXBizDataCrypt;

class Auto extends Controller
{

    //获取微信公众号配置信息
    public function config()
    {
        $config = Db::name("config")->find();
        return $config;
    }

    //获取微信用户基本信息
    public function wechat_info($openid){
        $WeChat = new WeChat();
        $result = $WeChat->user_info($openid);
        return $result;
    }


    //微信授权链接
    public function wx_url(){
        if(empty($_POST['openid'])){
            $openid = Session::get("openid");
        }else{
            $openid = $_POST['openid'];
            Session::set("openid",$_POST['openid']);
        }
        if(empty($openid)){
            $config = $this->config();
            if(empty($_POST['type'])){
                $base_url = "http://".$_SERVER['HTTP_HOST']."/h5?/";
            }else{
                //$base_url = "http://".$_SERVER['HTTP_HOST']."/h5/#/pages/index/subscribe?id=".$_POST['id']."/";
                $base_url = "http://".$_SERVER['HTTP_HOST']."/h5?id=".$_POST['id']."wx/";
            }
            //$base_url = urlencode($base_url);
            //$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$config['appid']}&redirect_uri={$base_url}&response_type=code&scope=snsapi_base&state={$state}#wechat_redirect";
            $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$config['appid']."&redirect_uri=".$base_url."&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect";
            $black['code'] = 0;
            $black['url'] = $url;
        }else{
            //获取用户基本信息
            $detail = Db::name("admin_fans")->where(['openid'=>$openid])->find();
            Session::set('USER_INFO_SESSION',$detail);
            $black['code'] = 1;
            $black['openid'] = $openid;
            $black['userinfo'] = $detail;
        }
        return json_encode($black);
    }

    public function user_info(){
        $code = $_GET['code'];
        $WeChat = new WeChat();
        $result = $WeChat->user_access_token($code);

        if($result['status']==1 || $result['status']==2){
            $openid = $result['data']['openid'];

            //注册用户
            $detail = Db::name("admin_fans")->where(['openid'=>$openid])->find();
//            $data['longitude'] = empty($_POST['longitude'])?Session::get("longitude"):$_POST['longitude'];
//            $data['latitude'] = empty($_POST['latitude'])?Session::get("latitude"):$_POST['latitude'];

            //拉取微信用户基本信息
            $wechat_info = $this->wechat_info($openid);
            if($wechat_info['status']==1){
                $wechat_info = $wechat_info['data'];
                if($wechat_info['subscribe']!=1){
                    $black['code'] = 1;
                    $black['msg'] = "请先关注公众号";
                    return json_encode($black);
                }
                $data['nickname'] = empty($wechat_info['nickname'])?'未授权用户':$wechat_info['nickname'];
                $data['avatar'] = empty($wechat_info['headimgurl'])?"":$wechat_info['headimgurl'];
                $data['sex'] = empty($wechat_info['sex'])?"":$wechat_info['sex'];
                $data['unionid'] = empty($result['data']['unionid'])?'':$result['data']['unionid'];
            }
            if(empty($detail)){
                $ip = request()->ip();
                $data['openid'] = $openid;
                $data['addtime'] = time();
                $data['register_ip'] = $ip;
                //注册操作
                $res = Db::name("admin_fans")->insert($data);
                $detail = $data;
            }else{
                $data['lasttime'] = date("Y-m-d H:i:s");
                $data['last_ip'] = request()->ip();
                Db::name("admin_fans")->where(['openid'=>$openid])->update($data);
                Db::name("admin_fans")->where(['openid'=>$openid])->setInc("number",1);
            }
            Session::set('USER_INFO_SESSION',$detail);
            Session::set("openid",$openid);
            setcookie('openid',$openid,time()+86400*30);
            $black['code'] = 0;
            $black['openid'] = $openid;
            $black['userinfo'] = $detail;
            return json_encode($black);
        }else{
            $black['code'] = 1;
            $black['msg'] = "授权失败";
            return json_encode($black);
        }
    }

    //小程序微信信息存储
    public function program(){
        require ROOT_PATH."extend/sample/wxBizDataCrypt.php";
        //$value = '{"openId":"o83Vf5UByuaLvGFkT_8vwo7lqExg","nickName":"李坤鹏","gender":1,"language":"zh_CN","city":"Yichang","province":"Hubei","country":"China","avatarUrl":"https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJCWpvVtU7gU22th0gHs9OYEknK4pHX3KZicsSpZnkJsyEVqV1LWlvJ6xgXJEicnDgDnia6BDppfhicXg/132","unionId":"oURNst_E8Wzh7ZIUo5zDXBepBPgA","watermark":{"timestamp":1602926628,"appid":"wx598641c99deb8edd"}}';
        try{
            $appid = $_POST['appid'];
            $config = Db::name("config")->where(['xcx_appid'=>$appid])->find();
            Session::set("thisWechat",$config);


            $appid = $config['xcx_appid'];
            $appSecret = $config['xcx_appsecret'];
            $encryptedData=$_POST['encryptedData'];
            $iv = $_POST['iv'];
            $code = $_POST['code'];
            $black = $this->sessionKey($code,$appid,$appSecret);
            //$sessionKey = 'tiihtNczf5v6AKRyjwEUhQ==';
            $sessionKey = $black['session_key'];
            $pc = new WXBizDataCrypt($appid, $sessionKey);
            $errCode = $pc->decryptData($encryptedData, $iv, $data );


            if ($errCode == 0) {
                $value = json_decode($data,true);
                $xcx_openid = $black['openid'];
                $unionId = empty($black['unionId'])?'':$black['unionId'];
                //存储粉丝信息
                //注册用户
                $detail = Db::name("admin_fans")->where(['xcx_openid'=>$xcx_openid])->find();
//            $data['longitude'] = empty($_POST['longitude'])?Session::get("longitude"):$_POST['longitude'];
//            $data['latitude'] = empty($_POST['latitude'])?Session::get("latitude"):$_POST['latitude'];
                if(empty($detail)){
                    $ip = request()->ip();
                    $dataVal['xcx_openid'] = $xcx_openid;
                    $dataVal['unionid'] = $unionId;
                    $dataVal['nickname'] = $value['nickName'];
                    $dataVal['avatar'] = $value['avatarUrl'];
                    $dataVal['addtime'] = time();
                    $dataVal['register_ip'] = $ip;
                    $dataVal['uniacid'] = $config['id'];
                    //注册操作
                    $id = Db::name("admin_fans")->insertGetId($dataVal);
                    $detail = $dataVal;
                }else{
                    $id = $detail['id'];
                    $dataVal['lasttime'] = date("Y-m-d H:i:s");
                    $dataVal['last_ip'] = request()->ip();
                    $dataVal['uniacid'] = $config['id'];
                    Db::name("admin_fans")->where(['xcx_openid'=>$xcx_openid])->setInc("number",1);
                    Db::name("admin_fans")->where(['xcx_openid'=>$xcx_openid])->update($dataVal);
                }

                $userinfo = Db::name("admin_fans")->where(['id'=>$id])->find();

                Session::set('USER_INFO_SESSION',$userinfo);
                Session::set("userid",$id);
                setcookie('userid',$id,time()+86400*30);
                $returnBlack['code'] = 0;
                $returnBlack['userid'] = $id;
                $returnBlack['userinfo'] = $userinfo;

                $this->bindremind("project_account",$id);

                return json_encode($returnBlack);
                print($data . "\n");
            } else {
                $returnBlack['code'] = 1;
                $returnBlack['msg'] = "授权失败";
                return json_encode($returnBlack);
                print($errCode . "\n");
            }
        }catch (Exception $e){
            echo $e->getMessage();
        }
    }


    //绑定小程序通知
    public function bindremind($table,$id){
        $project_user = Session::get("project_user");
        if(empty($project_user)){
            $black['code'] = 1;
            $black['msg'] = "请重新登录";
            echo json_encode($black);die;
        }
        //微信绑定
        Db::name($table)->where(['id'=>$project_user['id']])->update(['fans_id'=>$id]);
    }



    // code是js获取，前端传过来的哦。
    function sessionKey($code, $appId, $appSecret)
    {
        /**
         * code 换取 session_key
         * ​这是一个 HTTPS 接口，开发者服务器使用登录凭证 code 获取 session_key 和 openid。
         * 其中 session_key 是对用户数据进行加密签名的密钥。为了自身应用安全，session_key 不应该在网络上传输。
         */
        $url = 'https://api.weixin.qq.com/sns/jscode2session';
        $result = json_decode($this->curl($url, [
            'appid' => $appId,
            'secret' => $appSecret,
            'grant_type' => 'authorization_code',
            'js_code' => $code
        ]), true);
        if (isset($result['errcode'])) {
            return false;
        }
        return $result;
    }

    function curl($url, $data = [])
    {
        // 处理get数据
        if (!empty($data)) {
            $url = $url . '?' . http_build_query($data);
        }
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//这个是重点。
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }




    //app微信授权回调
    public function applogin(){
        try{
            $authResult = $_POST;
            $openid = $authResult['openid'];
            //注册用户
            $detail = Db::name("users_fans")->where(['openid'=>$openid])->find();
            if(empty($detail)){
                $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$authResult['access_token'].'&openid='.$authResult['openid'];
                $url=$this->CURLSend($url,'get');


                //获取请求结果,并将请求结果转换成json
                $wechat_info = json_decode($url,true);

                $data['nickname'] = empty($wechat_info['nickname'])?'未授权用户':$wechat_info['nickname'];
                $data['avatar'] = empty($wechat_info['headimgurl'])?"":$wechat_info['headimgurl'];
                $data['sex'] = empty($wechat_info['sex'])?"":$wechat_info['sex'];
                $data['unionid'] = $wechat_info['unionid'];


                $ip = request()->ip();
                $data['openid'] = $openid;
                $data['addtime'] = time();
                $data['register_ip'] = $ip;
                //注册操作
                $res = Db::name("users_fans")->insert($data);
                $detail = $data;
            }else{
                $data['lasttime'] = date("Y-m-d H:i:s");
                $data['last_ip'] = request()->ip();
                $data['login_number'] = $detail['login_number']+1;
                Db::name("users_fans")->where(['openid'=>$openid])->update($data);
            }
            $unionid = $detail['unionid'];
            //待优化代码块
            //$detail = Db::name("users")->where(['openid'=>$openid])->find();
            $detail = Db::name("users_fans")->where(['unionid'=>$unionid])->find();
            if (empty($detail)){
                $detail = Db::name("users_fans")->where(['openid'=>$openid])->find();
            }
            $detail['nickname'] = empty($detail['nickname'])?$detail['name']:$detail['nickname'];
            if(empty($detail['avatar'])){
                $detail['avatar'] = "https://".$_SERVER['HTTP_HOST']."/static/images/nopic-107.png";
            }else{
                if(!strstr($detail['avatar'], 'http')){
                    $detail['avatar'] = "https://".$_SERVER['HTTP_HOST'].$detail['avatar'];
                }
            }
            Session::set('USER_INFO_SESSION',$detail);

            Session::set("openid",$openid);
            setcookie('openid',$openid,time()+86400*30);
            $black['code'] = 0;
            $black['openid'] = $openid;
            $black['userinfo'] = $detail;
            return json_encode($black);
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = "授权失败";
            return json_encode($black);
        }
    }



    //生成随机字符串
    public function createtoken()
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        mt_srand(10000000 * (double)microtime());
        for ($i = 0, $str = '', $lc = strlen($chars) - 1; $i < 8; $i++) {
            $str .= $chars[mt_rand(0, $lc)];
        }
        return $str;
    }

    //token验证服务器
    public function token()
    {
        //引入WeChat
        $WeChat = new WeChat();
        $echostr1 = $this->createtoken();
        $nonce = empty($_GET["nonce"])?rand(10000,99999):$_GET["nonce"];
        $timestamp = empty($_GET['timestamp'])?time():$_GET['timestamp'];
        $echostr = empty($_GET['echostr'])?$echostr1:$_GET['echostr'];
        $signature = empty($_GET['signature'])?'':$_GET['signature'];
        $WeChat->token($nonce, $timestamp, $echostr, $signature);
    }


    //获取用户openid
    public function auto()
    {

        $openid=Session::get("openid")?Session::get("openid"):'';
        if(empty($openid))
        {
            $Wchat = new Wchat();
            //$t_url='https://'.$_SERVER['HTTP_HOST'].'/api/Auto/user_info';
            $t_url='https://'.$_SERVER['HTTP_HOST'].'/h5/';
            $Wchat->getOpenid($t_url);

            /*$info=$Wchat->getOpenid($t_url);
            if($info){
                $openid=$info['openid'];
                setcookie('openid',$openid,time()+86400*30);
            }*/
        }


        //引入WeChat
        /*$WeChat = new WeChat();
        $code = Session::get("user_access_token");
        //通过code获取access_token
        $result = $WeChat->user_access_token($code);

        //获取用户网页授权
        $result = $WeChat->user_refresh_token("REFRESH_TOKEN");

        $result = $WeChat->user_info();
        var_dump($result);die;*/
    }

    //网页请求
    public function CURLSend($url, $method = 'get', $data = ''){
        $ch = curl_init();//初始化
        $headers = array('Accept-Charset: utf-8');
        //设置URL和相应的选项
        curl_setopt($ch, CURLOPT_URL, $url);//指定请求的URL
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));//提交方式
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//不验证SSL
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);//不验证SSL
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);//设置HTTP头字段的数组
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible;MSIE5.01;Windows NT 5.0)');//头的字符串

        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);//自动设置header中的Referer:信息
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//提交数值
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//是否输出到屏幕上,true不直接输出
        $temp = curl_exec($ch);//执行并获取结果
        curl_close($ch);
        return $temp;//return 返回值
    }


    /*public function user_info(){
        $code = $_GET['code'];
        $WeChat = new WeChat();
        $result = $WeChat->user_access_token($code);

        if($result['status']==1 || $result['status']==2){
            $openid = $result['data']['openid'];
            Session::set("openid",$openid);
            setcookie('openid',$openid,time()+86400*30);
        }
    }*/


    function newtext($params){
        $myfile = fopen(__DIR__."/newfile.txt", "a") or die("Unable to open file!");//这个是在c盘根目录生成文件
        $txt = $params;//获取参数
        $b="";
        foreach($txt as $k=>$v){
            $b = $b ."[".$k."]=>".$v."\n";
        }
        fwrite($myfile, $b);//写入内容,可以写多次哦,不过没啥意义,因为你拼接好字符串,一次写入就行了
        fclose($myfile);//关闭该操作
    }


    function newtext1($params){
        $myfile = fopen(__DIR__."/newfile1.txt", "a") or die("Unable to open file!");//这个是在c盘根目录生成文件
        $txt = $params;//获取参数

        fwrite($myfile, $txt);//写入内容,可以写多次哦,不过没啥意义,因为你拼接好字符串,一次写入就行了
        fclose($myfile);//关闭该操作
    }

}